package com.explment.lens.service.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.explment.lens.entity.SysUserEntity;
import com.explment.lens.entity.securityuser.LoginUser;
import com.explment.lens.exception.BusinessException;
import com.explment.lens.service.SysUserService;
import com.explment.lens.utils.result.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service("securityUserDetailService")
public class SecurityUserDetailService implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 这里应该调用 sysUserService 来查询用户信息，并将其转换为 UserDetails 对象
        SysUserEntity user = sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("account", username));
        if (user != null) {
            // 这里应该将用户信息转换为 LoginUser 对象，而不是直接返回 SysUserEntity
            LoginUser loginUser = new LoginUser();
            loginUser.setUsername(user.getAccount());
            loginUser.setPassword(user.getPassword());
            loginUser.setId(user.getId().toString());
            loginUser.setTenantId(user.getTenantId());
            return loginUser;
        }

        throw new BusinessException(ResultCode.BAD_REQUEST,"User not found");

    }
}
